﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;

namespace Imgalib.Utility
{
    public class JsonUtility
    {
        /// <summary>
        /// Convert List of objects to Json
        /// </summary>
        /// <typeparam name="T">Type of object</typeparam>
        /// <param name="items">Object list to convert</param>
        /// <returns>Json string that can be identified by Jquery</returns>
        public String ConvertToJson<T>(List<T> items)
        {
            StringBuilder strJson = new StringBuilder();
            strJson.AppendLine("[");
            foreach (T item in items)
            {
                String str1 = SerializeObjectIntoJson<T>(item);
                strJson.AppendLine(str1);
                strJson.AppendLine(",");
            }
            String json = strJson.ToString();
            json = json.Substring(0, json.LastIndexOf(","));
            json = json + "]";

            return json;
        }


        private static string SerializeObjectIntoJson<T>(T p)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(p.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, p);
                ms.Flush();
                byte[] bytes = ms.GetBuffer();
                string jsonString = Encoding.UTF8.GetString(bytes, 0, bytes.Length).Trim('\0');
                return jsonString;
            }
        }

    }
}
